import {login, logout, getInfo} from '@/api/acl/user'
import {getToken, setToken, removeToken} from '@/utils/auth'
import  {resetRouter, allAsyncRoutes, constantRoutes, anyRoute} from '@/router'
import router from '@/router'
import cloneDeep from 'lodash/cloneDeep'


//根据返回的路由名称数组过滤用户真正的异步路由数组
function filterUserAsyncRoutes(allAsyncRoutes, routeNames) {
  const result=allAsyncRoutes.filter(item=>{
    if (routeNames.indexOf(item.name)!==-1){
      if (item.children&&item.children.length>0){
        item.children=filterUserAsyncRoutes(item.children,routeNames)
      }
      return true
    }
  })
  return result
}

const state = {
  token: localStorage.getItem('TOKEN'),
  name: '',
  avatar: '',
  buttons: [],
  roles: [],
  routes:[],//代表这个永辉读音的所有的路由数组,用于后期根据它动态生成菜单去用(v-for)
  asyncRoutes: []// 准备放用户返回的字符串信息对应的真正的异步路由
}
const mutations = {
  //token
  SET_TOKEN(state, token) {
    state.token = token
  },
  //commit用户信息
  SET_USERINFO(state, userInfo) {
    state.name = userInfo.name
    state.avatar = userInfo.avatar
    state.buttons=userInfo.buttons
    state.roles=userInfo.roles
  },
  //清空state中的数据
  RESET_STATE(state) {
    state.name = ''
    state.avatar = ''
    state.token = ''
  },
  //动态添加路由
  SET_ROUTES(state, asyncRoutes) {
    state.asyncRoutes = asyncRoutes
    state.routes = constantRoutes.concat(asyncRoutes, anyRoute)
    //动态注册路由(动态添加路由)
    router.addRoutes([...asyncRoutes, anyRoute])
  }
}
const actions = {
  //登录
  async login({commit}, userInfo) {
    const {username, password} = userInfo
    try {
      const result = await login({username: username.trim(), password: password})
      if (result.code === 200 || result.code === 20000) {
        commit('SET_TOKEN', result.data.token)
        localStorage.setItem('TOKEN', result.data.token)
      }
    } catch (error) {
      this.$message.error('登录失败')
    }
  },
  //获取用户信息
  async getInfo({commit, state}) {
    const result = await getInfo(state.token)
    try {
      if (result.code === 200 || result.code === 20000) {
        commit('SET_USERINFO', result.data)
        commit('SET_ROUTES', filterUserAsyncRoutes(cloneDeep(allAsyncRoutes), result.data.routes))
      }
    } catch (error) {
      this.$message.error('获取用户信息失败')
    }
  },
  //退出登录
  async logout({commit, state}) {
    try {
      const result = await logout(state.token)
      if (result.code === 200 || result.code === 20000) {
        //清空state中的token
        commit('RESET_STATE')
        //重置路由
        resetRouter()
        //清空localStorage中的token
        localStorage.removeItem('TOKEN')
      }
    } catch (error) {
      this.$message.error('退出登录失败')
    }
  },
  //清空token
  resetToken({commit}) {
    commit('RESET_STATE')
    localStorage.removeItem('TOKEN')
  },
}
/*}*/

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

